package com.zf.shuashua.advert.mg;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.aliyun.svideo.common.utils.AppInfoUtils;
import com.blankj.utilcode.util.AppUtils;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.liulishuo.filedownloader.util.FileDownloadUtils;
import com.zf.shuashua.R;
import com.zf.shuashua.ShuaApplication;

import java.io.File;

public class BrowserActivity extends AppCompatActivity {

    private WebView webview;

    private String mTitle;
    private String mUrl;
    protected AdDataBean mAdDataBean;

    public static void action(Context context, String title, String url, AdDataBean adDataBean) {
        Intent intent = new Intent(context, BrowserActivity.class);
        intent.putExtra("title", title);
        intent.putExtra("url", url);
        intent.putExtra("AdDataBean", adDataBean);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_browser);

        ImageView ivBack = findViewById(R.id.iv_back);
        TextView tvTitle = findViewById(R.id.tv_title);
        webview = findViewById(R.id.webContainer);
        initWebView();

        handleIntent();

        ivBack.setOnClickListener(v -> finish());

        tvTitle.setText(mTitle);

        requestUrl();
    }

    private void handleIntent() {
        mTitle = getIntent().getStringExtra("title");
        mUrl = getIntent().getStringExtra("url");
        mAdDataBean = (AdDataBean) getIntent().getSerializableExtra("AdDataBean");
    }

    @SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface"})
    private void initWebView() {
        WebSettings ws = webview.getSettings();
        // 网页内容的宽度是否可大于WebView控件的宽度
        ws.setLoadWithOverviewMode(false);
        // 保存表单数据
        ws.setSaveFormData(true);
        // 是否应该支持使用其屏幕缩放控件和手势缩放
        ws.setSupportZoom(true);
        ws.setBuiltInZoomControls(true);
        ws.setDisplayZoomControls(false);
        // 启动应用缓存
        ws.setAppCacheEnabled(true);
        // 设置缓存模式
        ws.setCacheMode(WebSettings.LOAD_DEFAULT);
        // setDefaultZoom  api19被弃用
        // 设置此属性，可任意比例缩放。
        ws.setUseWideViewPort(true);
        // 不缩放
        webview.setInitialScale(100);
        // 告诉WebView启用JavaScript执行。默认的是false。
        ws.setJavaScriptEnabled(true);
        //  页面加载好以后，再放开图片
        ws.setBlockNetworkImage(false);
        // 使用localStorage则必须打开
        ws.setDomStorageEnabled(true);
        // 排版适应屏幕
        ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        // WebView是否新窗口打开(加了后可能打不开网页)
//        ws.setSupportMultipleWindows(true);

        // webview从5.0开始默认不允许混合模式,https中不能加载http资源,需要设置开启。
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            ws.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        /** 设置字体默认缩放大小(改变网页字体大小,setTextSize  api14被弃用)*/
        ws.setTextZoom(100);
        //支持内容重新布局
        webview.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);

//        mWebChromeClient = new MyWebChromeClient(this);
//        webview.setWebChromeClient(mWebChromeClient);
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
            }

            @Override
            public void onPageFinished(WebView view, String url) {
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if(!TextUtils.isEmpty(url) &url.endsWith(".apk")){
                    startDownload(url);
                    return true;
                }
//                view.loadUrl(url);
                return false;
//                return super.shouldOverrideUrlLoading(view, url);
            }
        });
    }

    private void startDownload(String url) {
        Toast.makeText(BrowserActivity.this, "开始下载", Toast.LENGTH_LONG).show();
        MGReportManager.getInstance().startReport(ReportLocationType.startDown, mAdDataBean);
        FileDownloader.setup(this);
        final String savePath = FileDownloadUtils.getDefaultSaveRootPath() + File.separator;
        FileDownloader.getImpl().create(url).setPath(savePath, true).setListener(new FileDownloadListener() {
            @Override
            protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            }

            @Override
            protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
            }

            @Override
            protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            }

            @Override
            protected void blockComplete(BaseDownloadTask task) {
            }

            @Override
            protected void retry(final BaseDownloadTask task, final Throwable ex, final int retryingTimes, final int soFarBytes) {
            }

            @Override
            protected void completed(BaseDownloadTask task) {
//                MLog.logd("下载完成：" + task.getTargetFilePath());
                MGReportManager.getInstance().startReport(ReportLocationType.endDown, mAdDataBean);
                MGReportManager.getInstance().startReport(ReportLocationType.startInstall, mAdDataBean);
                String packageName = AppInfoUtils.getPackage(ShuaApplication.context, task.getTargetFilePath());
                if(!TextUtils.isEmpty(packageName)){
                    ShuaApplication.adMap.put(packageName, mAdDataBean);
                }
                AppUtils.installApp(task.getTargetFilePath());
            }

            @Override
            protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            }

            @Override
            protected void error(BaseDownloadTask task, Throwable e) {
            }

            @Override
            protected void warn(BaseDownloadTask task) {
            }
        }).start();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        handleIntent();

        requestUrl();
        super.onNewIntent(intent);
    }

    private void requestUrl() {
        if (webview != null && !TextUtils.isEmpty(mUrl)) {
            webview.loadUrl(mUrl);
        }
    }

    @Override
    protected void onDestroy() {
        if (webview != null) {
            webview.destroy();
        }
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            if (webview.canGoBack()) {
                webview.goBack(); //goBack()表示返回WebView的上一页面
                return true;
            } else {
                return super.onKeyDown(keyCode, event);
            }
        }
        return false;
    }

}
